'use strict'
const consola = require('consola')

const koa = require('koa')
const app = new koa()

const session = require('koa-session');

app.keys = ['some secret hurr'];
app.use(session({
  key: 'apis_news',
  maxAge: 86400000
}, app));

// 导入数据库信息
const config = require('./dbs/config')
const mongoose = require('mongoose')

// 导入路由
const Interface = require('./controllers/index')
const routerKeys = Object.keys(Interface)

// 导入返回数据格式
global.success = require('./common').message.success
global.fail = require('./common').message.fail
global.expire = {}
global.expire.userToken = require('./common').expire.userExpireTime
global.expire.sms = require('./common').expire.smsExpireTime

// 注册工具库
const utils = require('./utils')
global.utils = {}
for(let i in utils) {
  for(let j in utils[i]) {
    global.utils[j] = utils[i][j]
  }
}


const start = async() => {
  // 连接数据库
  await mongoose.connect(config.dataBase.dbs, {
    useNewUrlParser: true
  }, err => {
    if (err) return consola.error('数据库连接失败：' + err)
    consola.success({
      message: '数据库连接成功',
      badge: true
    })
  })

  // 注册路由
  await routerKeys.forEach(item => {
    app.use(Interface[item].routes()).use(Interface[item].allowedMethods())
  })

  // 启动项目，监听端口
  await app.listen(config.service.port, config.service.host, err => {
    if (err) return consola.error('server端工程启动失败：' + err)
    consola.success({
      message: `server端工程启动成功： http://${config.service.host}:${config.service.port}`,
      badge: true
    })
  })
}

start()